import Vue from 'vue';
import ComAlert from '~/components/Alert'  // 引入 overlay 组件
const Alert = Vue.extend(ComAlert)
const getDOM = function (dom) {
  if (dom.nodeType === 3) {
    dom = dom.nextElementSibling || dom.nextSibling
    getDOM(dom)
  }
  return dom
}
export default ({ app }, inject) => {
  let instance;
  let bodyStyle;

  function clear(vm){
    vm.$destroy();
    vm.$el.remove();
    document.body.style.overflow = bodyStyle;
  }
  const alert = function (config) {
    return new Promise((resolve,reject)=>{
      let title,content,okText,cancelText,cancel = false;
      if(toString.call(config) === '[object String]'){
        title = config;
      }else if(toString.call(config) === '[object Object]'){
        title = config.title;
        content = config.content;
        cancel = config.cancel;
        okText = config.okText;
        cancelText = config.cancelText
      }else{
        throw new TypeError('传入类型错误')
      }
      if(instance){
        clear(instance)
      }
      instance =  new Alert({
        el: document.createElement('div'),
        propsData:{
          title,
          content,
          cancel,
          okText,
          cancelText
        }
      });
      document.body.appendChild(instance.$el);
      // 禁止页面滚动
      bodyStyle = document.body.style.overflow
      document.body.style.overflow = 'hidden'

      instance.$on('close',function(e){
        reject();
        clear(instance);
      })
      instance.$on('ok',resolve);
      instance.$on('cancel',function(e){
        reject();
        clear(instance);
      });
    });
  }

  inject('alert',alert);

}
